<template>
  <div class="comments-container">
    <div class="header">
      <h2>评论管理</h2>
      <div class="stats">
        <el-statistic title="总评论数" :value="total" />
        <!-- <el-statistic title="今日评论" :value="todayComments" />
        <el-statistic title="待审核评论" :value="pendingComments" /> -->
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="评论用户">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="comments" stripe style="width: 100%" :row-key="(row) => row.id">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="评论用户" width="120" />
        <el-table-column prop="upvoteList" label="点赞数" width="120">
          <template #default="{ row }">
            <el-tag type="success" size="small">
              <el-icon>
                <Star />
              </el-icon>
              {{ row.upvoteList || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="createTime" label="评论时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 评论详情对话框 -->
    <el-dialog v-model="detailVisible" title="评论详情" width="600px" :before-close="handleDetailClose">
      <div v-if="currentComment" class="comment-detail">
        <div class="detail-item">
          <label>商品名称：</label>
          <span>{{ currentComment.productName }}</span>
        </div>
        <div class="detail-item">
          <label>评论用户：</label>
          <span>{{ currentComment.userName }}</span>
        </div>
        <div class="detail-item upvote-section">
          <label>点赞数：</label>
          <div class="upvote-display">
            <el-tag type="success" size="large" class="upvote-tag">
              <el-icon class="star-icon">
                <Star />
              </el-icon>
              <span class="upvote-count">{{ currentComment.upvoteList || 0 }}</span>
              <span class="upvote-text">赞</span>
            </el-tag>
          </div>
        </div>
        <div class="detail-item">
          <label>评论时间：</label>
          <span>{{ formatDate(currentComment.createTime) }}</span>
        </div>
        <div class="detail-item">
          <label>评论内容：</label>
          <div class="content">{{ currentComment.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Star } from '@element-plus/icons-vue'
import type { Comment } from '@/types'
import { formatDate } from '@/utils/date'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const comments = ref<Comment[]>([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
// const todayComments = ref(25)
// const pendingComments = ref(5)
const detailVisible = ref(false)
const currentComment = ref<Comment | null>(null)

// 搜索表单 - 匹配后端参数名
const searchForm = reactive({
  productName: '',
  userName: ''
})

// 获取评论列表
const loadComments = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...(searchForm.productName && { productName: searchForm.productName }),
      ...(searchForm.userName && { userName: searchForm.userName })
    }

    const response = await request.get('/evaluations/list', { params }) as any

    if (response && response.data) {
      const pageData = response.data
      // 确保数据是数组
      const dataArray = Array.isArray(pageData.data) ? pageData.data : []
      comments.value = dataArray
      total.value = pageData.allRow || 0
      currentPage.value = pageData.pageNum || 1
      pageSize.value = pageData.pageSize || 5
    } else {
      // 如果API调用失败，确保comments是空数组
      comments.value = []
      ElMessage.error(response?.message || '获取评论列表失败')
    }
  } catch (error: any) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')

  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadComments()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    productName: '',
    userName: ''
  })
  currentPage.value = 1
  loadComments()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadComments()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadComments()
}

// 查看评论详情
const handleView = (row: Comment) => {
  currentComment.value = row
  detailVisible.value = true
}

// 删除评论 - 匹配后端删除接口
const handleDelete = async (row: Comment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.userName}"对商品"${row.productName}"的评论吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.delete(`/evaluations/delete/${row.id}`)

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      loadComments()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentComment.value = null
}

// 确保数据初始化
onMounted(() => {
  // 确保comments是数组
  if (!Array.isArray(comments.value)) {
    comments.value = []
  }
  loadComments()
})
</script>

<style scoped lang="scss">
.comments-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-color;
    }

    .stats {
      display: flex;
      gap: 20px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}

.comment-detail {
  .detail-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;

    label {
      width: 100px;
      font-weight: bold;
      color: $text-color;
    }

    span {
      flex: 1;
      color: $text-color-regular;
    }

    .content {
      flex: 1;
      color: $text-color-regular;
      line-height: 1.6;
      white-space: pre-wrap;
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
    }

    &.upvote-section {
      align-items: center;

      .upvote-display {
        flex: 1;
        display: flex;
        align-items: center;

        .upvote-tag {
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          border: none;
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
          }

          .star-icon {
            color: #fff;
            margin-right: 6px;
            font-size: 16px;
            animation: star-pulse 2s ease-in-out infinite;
          }

          .upvote-count {
            color: #fff;
            font-weight: bold;
            font-size: 16px;
            margin-right: 4px;
          }

          .upvote-text {
            color: #fff;
            font-size: 14px;
          }
        }
      }
    }
  }
}

@keyframes star-pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }
}
</style>